package com.gomore.opple.module.gooddetail;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.gomore.opple.R;
import com.gomore.opple.common.GlobalConstant;
import com.gomore.opple.model.EventShoppingCar;
import com.gomore.opple.module.BaseFragment;
import com.gomore.opple.module.IntentStart;
import com.gomore.opple.module.gooddetail.adapter.MyGridViewAdapter;
import com.gomore.opple.module.gooddetail.adapter.MyListViewAdapter;
import com.gomore.opple.rest.shopcart.SaveShoppingCartRequest;
import com.gomore.opple.utils.BigDecimalUtils;
import com.gomore.opple.utils.DensityUtil;
import com.gomore.opple.utils.DialogUtils;
import com.gomore.opple.utils.GlideImageLoader;
import com.gomore.opple.web.cgform.goods.entity.TOGoodsEntity;
import com.gomore.opple.widgets.MyGridView;
import com.gomore.opple.widgets.MyListView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;


/**
 * Created by robot
 */
public class GoodDetailFragment extends BaseFragment implements GoodDetailContract.View, OnBannerClickListener {

    @Bind(R.id.shellLayout)
    RelativeLayout shellLayout;
    @Bind(R.id.banner)
    Banner banner;
    //覆盖banner,添加到购物车对象
    @Bind(R.id.copy_up)
    ImageView copy_up;
    //商品介绍
    @Bind(R.id.good_number)
    TextView good_number;
    @Bind(R.id.good_name)
    TextView good_name;
    @Bind(R.id.good_brand)
    TextView good_brand;
    @Bind(R.id.good_inv)
    TextView good_inv;
    @Bind(R.id.good_price)
    TextView good_price;
    //参数表格
    @Bind(R.id.my_list_view)
    MyListView my_list_view;
    //商品详情
    @Bind(R.id.pic_my_grid_view)
    MyGridView pic_my_grid_view;
    //选择
    @Bind(R.id.min)
    ImageView min;
    @Bind(R.id.good_quanity)
    EditText good_quanity;
    @Bind(R.id.add)
    ImageView add;
    @Bind(R.id.add_to_shopping_car)
    TextView add_to_shopping_car;
    //头部
    @Bind(R.id.back)
    LinearLayout back;
    @Bind(R.id.shopping_car)
    ImageView shopping_car;
    private MyGridViewAdapter myGridViewAdapter;
    private MyListViewAdapter myListViewAdapter;
    private GoodDetailContract.Presenter mPresenter;
    private String goodId;
    //动画
    private float[] mCurrentPosition = new float[2];
    private PathMeasure mPathMeasure;
    private static GoodDetailActivity goodDetailActivity;

    public static GoodDetailFragment getInstance(GoodDetailActivity mgoodDetailActivity) {
        goodDetailActivity = mgoodDetailActivity;
        return new GoodDetailFragment();
    }

    @Override
    protected int getLayoutView() {
        return R.layout.fragment_good_detail;
    }

    @Override
    protected void initalizeData() {
        if (getArguments() != null && getArguments().getString(IntentStart.GOODID) != null) {
            goodId = getArguments().getString(IntentStart.GOODID);
        }
        int width = DensityUtil.screenWith(getActivity());
        int height = width * 7 / 10;
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(width, height);
        banner.setLayoutParams(layoutParams);
        copy_up.setLayoutParams(layoutParams);
    }

    @Override
    protected void initalizeViews() {
        mPresenter.prepareInitData();
        if (goodId != null) {
            mPresenter.getGoodById(goodId);
        }
        good_quanity.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(editable.toString().trim()) || editable.toString().trim().equals("0")) {
                    good_quanity.setText("1");
                }
                good_quanity.setSelection(editable.toString().trim().length());
            }
        });

        min.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!good_quanity.getText().toString().trim().equals("1")) {
                    BigDecimal bigDecimal = new BigDecimal(good_quanity.getText().toString().trim());
                    bigDecimal = bigDecimal.subtract(new BigDecimal(1));
                    good_quanity.setText(bigDecimal.toString());
                }
            }
        });

        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BigDecimal bigDecimal = new BigDecimal(good_quanity.getText().toString().trim());
                bigDecimal = bigDecimal.add(new BigDecimal(1));
                good_quanity.setText(bigDecimal.toString());
            }
        });
    }


    @Override
    public void setPresenter(GoodDetailContract.Presenter presenter) {
        mPresenter = presenter;
    }

    @Override
    public void showProgressDialog() {
        if (getActivity() == null) {
            DialogUtils.showLoadingDialog(getActivity(), getResources().getString(R.string.loading));
        } else {
            DialogUtils.showLoadingDialog(goodDetailActivity, getResources().getString(R.string.loading));
        }
    }

    @Override
    public void hideProgressDialog() {
        DialogUtils.closeLoadingDialog();
    }

    @Override
    public void showMessage(String msg) {
        showToast(msg);
    }

    @Override
    public void showMessage(int msgId) {
        showToast(msgId);
    }

    @Override
    public void showContentView(TOGoodsEntity toGoodsEntity) {
        //展示banner图
        good_quanity.setText("1");
        String[] bannersArray = toGoodsEntity.getPictures().split(",");
        List<String> bannerList = Arrays.asList(bannersArray);
        disPlayBanner(bannerList);
        showDetail(toGoodsEntity);
        showTableLayout(getTableLayoutData(toGoodsEntity));
        showPictures(toGoodsEntity);
    }

    @Override
    public void finish() {
        getActivity().finish();
    }

    @OnClick({R.id.back, R.id.shopping_car, R.id.add_to_shopping_car})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                getActivity().finish();
                break;
            case R.id.shopping_car:
                EventShoppingCar eventShoppingCar = new EventShoppingCar();
                eventShoppingCar.setIsClick(true);
                EventBus.getDefault().post(eventShoppingCar);
                finish();
                break;
            case R.id.add_to_shopping_car:
                if (TextUtils.isEmpty(good_quanity.getText().toString().trim())) {
                    showMessage(R.string.good_number);
                    return;
                }
                //判断是否超过库存数量
                BigDecimal bigDecimalInput = new BigDecimal(good_quanity.getText().toString().trim());
                BigDecimal bigDecimal = new BigDecimal(mPresenter.getTOGoodsEntity().getInv());
                int compare = bigDecimalInput.compareTo(bigDecimal);
                if (compare > 0) {
                    showMessage(R.string.out_number);
                    return;
                }
                //是否选择客户
                if (mPresenter.getConsumer() == null || mPresenter.getConsumer().getId() == null) {
                    showMessage(R.string.select_consumetr);
                    return;
                }
                //商品是否存在
                if (mPresenter.getTOGoodsEntity() == null || mPresenter.getTOGoodsEntity().getId() == null) {
                    showMessage(R.string.good_error);
                    return;
                }
                if (mPresenter.getTOGoodsEntity().getPictures() != null) {
                    copy_up.setVisibility(View.VISIBLE);
                    banner.setVisibility(View.GONE);
                    addToCarAnimation(copy_up);
                } else {
                    SaveShoppingCartRequest saveShoppingCartRequest = new SaveShoppingCartRequest();
                    saveShoppingCartRequest.setConsumerId(mPresenter.getConsumer().getId());
                    saveShoppingCartRequest.setGoodsId(mPresenter.getTOGoodsEntity().getId());
                    saveShoppingCartRequest.setCount(good_quanity.getText().toString().trim());
                    saveShoppingCartRequest.setAttachmentUrl("");
                    mPresenter.addToShoppingCar(saveShoppingCartRequest);
                }
                break;
        }
    }

    public void disPlayBanner(List<String> banners) {
        //覆盖ImageView加载图片
        Glide.with(getActivity())
                .load(banners.get(0))
                .asBitmap()
                .placeholder(R.mipmap.goods_place)
                .error(R.mipmap.goods_place)
                .into(copy_up);

        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(banners);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //点击事件
        banner.setOnBannerClickListener(this);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    @Override
    public void OnBannerClick(int position) {

    }

    private void showDetail(TOGoodsEntity toGoodsEntity) {
        if (toGoodsEntity.getCode() != null) {
            good_number.setText(toGoodsEntity.getCode());
        }
        if (toGoodsEntity.getName() != null) {
            good_name.setText(toGoodsEntity.getName());
        }
        if (toGoodsEntity.getCompany() != null) {
            good_brand.setText(toGoodsEntity.getCompany());
        }
        good_inv.setText("" + toGoodsEntity.getInv());
        BigDecimal str = BigDecimalUtils.forMate(toGoodsEntity.getTagPrice());
        good_price.setText("¥" + str.toString());
    }

    private void showTableLayout(List<String> stringList) {
        myListViewAdapter = new MyListViewAdapter(getActivity(), GlobalConstant.TableRows.titleList(), stringList);
        my_list_view.setAdapter(myListViewAdapter);
    }

    private void showPictures(TOGoodsEntity toGoodsEntity) {
        String[] picturesArray = toGoodsEntity.getDetailedIntro().split(",");
        List<String> PictureList = Arrays.asList(picturesArray);
        myGridViewAdapter = new MyGridViewAdapter(getActivity(), PictureList);
        pic_my_grid_view.setAdapter(myGridViewAdapter);
    }

    private List<String> getTableLayoutData(TOGoodsEntity toGoodsEntity) {
        List<String> stringList = new ArrayList<>();
        for (int i = 0; i < GlobalConstant.TableRows.titleList().size(); i++) {
            if (i == 0) {
                if (!TextUtils.isEmpty(toGoodsEntity.getCompany())) {
                    stringList.add(toGoodsEntity.getCompany());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 1) {
                if (!TextUtils.isEmpty(toGoodsEntity.getColorTemperature())) {
                    stringList.add(toGoodsEntity.getColorTemperature());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 2) {
                if (!TextUtils.isEmpty(toGoodsEntity.getGoodsStyle())) {
                    stringList.add(toGoodsEntity.getGoodsStyle());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 3) {
                if (!TextUtils.isEmpty(toGoodsEntity.getArea())) {
                    stringList.add(toGoodsEntity.getArea());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 4) {
                if (!TextUtils.isEmpty(toGoodsEntity.getInstallMethod())) {
                    stringList.add(toGoodsEntity.getInstallMethod());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 5) {
                if (!TextUtils.isEmpty(toGoodsEntity.getSpec())) {
                    stringList.add(toGoodsEntity.getSpec());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 6) {
                if (!TextUtils.isEmpty(toGoodsEntity.getLightSource())) {
                    stringList.add(toGoodsEntity.getLightSource());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 7) {
                if (!TextUtils.isEmpty(toGoodsEntity.getPower())) {
                    stringList.add(toGoodsEntity.getPower());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 8) {
                if (!TextUtils.isEmpty(toGoodsEntity.getSize())) {
                    stringList.add(toGoodsEntity.getSize());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 9) {
                if (!TextUtils.isEmpty(toGoodsEntity.getLightNumber())) {
                    stringList.add(toGoodsEntity.getLightNumber());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 10) {
                if (!TextUtils.isEmpty(toGoodsEntity.getMaterial())) {
                    stringList.add(toGoodsEntity.getMaterial());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 11) {
                if (!TextUtils.isEmpty(toGoodsEntity.getSeries())) {
                    stringList.add(toGoodsEntity.getSeries());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 12) {
                if (!TextUtils.isEmpty(toGoodsEntity.getFunction())) {
                    stringList.add(toGoodsEntity.getFunction());
                } else {
                    stringList.add("***");
                }
            }
            if (i == 13) {
                if (!TextUtils.isEmpty(toGoodsEntity.getSpace())) {
                    stringList.add(toGoodsEntity.getSpace());
                } else {
                    stringList.add("***");
                }
            }

        }
        return stringList;
    }

    private void addToCarAnimation(ImageView goodsImg) {
        //获取需要进行动画的ImageView
        final ImageView animImg = new ImageView(getActivity());
        animImg.setImageDrawable(goodsImg.getDrawable());
        //图片初始化大小
        int screenWidth = DensityUtil.screenWith(getActivity());
        int width = (screenWidth - DensityUtil.dip2px(getActivity(), 10 + 12 + 12)) / 2;
        int height = (width * 13) / 17;
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width, height);
        shellLayout.addView(animImg, params);
        //设置位置
        final int shellLocation[] = new int[2];
        shellLayout.getLocationInWindow(shellLocation);
        int animImgLocation[] = new int[2];
        goodsImg.getLocationInWindow(animImgLocation);
        int carLocation[] = new int[2];
        shopping_car.getLocationInWindow(carLocation);

        // 起始点：图片起始点-父布局起始点+该商品图片的一半-图片的marginTop || marginLeft 的值
        float startX = animImgLocation[0] - shellLocation[0] + goodsImg.getWidth() / 2 - DensityUtil.dip2px(getActivity(), 10.0f);
        float startY = animImgLocation[1] - shellLocation[1] + goodsImg.getHeight() / 2 - DensityUtil.dip2px(getActivity(), 10.0f);

        // 商品掉落后的终点坐标：购物车起始点-父布局起始点
        float endX = carLocation[0] - shellLocation[0] - 4 * shopping_car.getWidth();
        float endY = carLocation[1] - shellLocation[1] - 2 * shopping_car.getWidth();

        //控制点，控制贝塞尔曲线
        float ctrlX = (startX + endX) / 2;
        float ctrlY = startY - 100;

        Log.e("num", "-------->" + ctrlX + " " + startY + " " + ctrlY + " " + endY);

        Path path = new Path();
        path.moveTo(startX, startY);
        // 使用二阶贝塞尔曲线
        path.quadTo(ctrlX, ctrlY, endX, endY);
        mPathMeasure = new PathMeasure(path, false);
        //图片大小
        ObjectAnimator scaleXanim = ObjectAnimator.ofFloat(animImg, "scaleX", 1, 0.7f, 0.5f, 0.3f, 0.1f);
        ObjectAnimator scaleYanim = ObjectAnimator.ofFloat(animImg, "scaleY", 1, 0.7f, 0.5f, 0.3f, 0.1f);

        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                float value = (Float) animation.getAnimatedValue();
                // 获取当前点坐标封装到mCurrentPosition
                // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距离的坐标点和切线，
                // pos会自动填充上坐标，这个方法很重要。
                // mCurrentPosition此时就是中间距离点的坐标值
                mPathMeasure.getPosTan(value, mCurrentPosition, null);
                // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                animImg.setTranslationX(mCurrentPosition[0]);
                animImg.setTranslationY(mCurrentPosition[1]);
            }
        });


        valueAnimator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                // 把执行动画的商品图片从父布局中移除
                shellLayout.removeView(animImg);
                //添加到购物车
                SaveShoppingCartRequest saveShoppingCartRequest = new SaveShoppingCartRequest();
                saveShoppingCartRequest.setConsumerId(mPresenter.getConsumer().getId());
                saveShoppingCartRequest.setGoodsId(mPresenter.getTOGoodsEntity().getId());
                saveShoppingCartRequest.setCount(good_quanity.getText().toString().trim());
                saveShoppingCartRequest.setAttachmentUrl("");
                mPresenter.addToShoppingCar(saveShoppingCartRequest);
            }
        });
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.setDuration(1500);
        animatorSet.setInterpolator(new AccelerateInterpolator());
        animatorSet.playTogether(scaleXanim, scaleYanim, valueAnimator);
        animatorSet.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Glide.get(getActivity()).clearMemory();//清理内存缓存  可以在UI主线程中进行
        System.gc();
    }
}
